// src/pages/Home/RoleManagement/RoleList.jsx
import React, { useState } from 'react';
import {Table, Tag, Space, Button, Modal, Form, Checkbox, message, Input} from 'antd';
import { PlusOutlined } from '@ant-design/icons';

const permissionsList = [
  { key: 'user:view', name: '查看用户' },
  { key: 'user:create', name: '创建用户' },
  { key: 'user:edit', name: '编辑用户' },
  { key: 'user:delete', name: '删除用户' },
  { key: 'role:manage', name: '管理角色' },
  { key: 'data:view', name: '查看数据' },
  { key: 'data:create', name: '创建数据' },
  { key: 'data:edit', name: '编辑数据' },
  { key: 'data:delete', name: '删除数据' },
];

const RoleList = () => {
  const [roles, setRoles] = useState([
    { id: '1', name: '管理员', permissions: ['user:view', 'user:create', 'user:edit', 'user:delete', 'role:manage', 'data:view', 'data:create', 'data:edit', 'data:delete'] },
    { id: '2', name: '普通用户', permissions: ['user:view', 'data:view'] },
    { id: '3', name: '数据专员', permissions: ['data:view', 'data:create', 'data:edit'] },
  ]);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingRole, setEditingRole] = useState(null);
  const [form] = Form.useForm();

  const handleCreate = () => {
    form.resetFields();
    setEditingRole(null);
    setIsModalOpen(true);
  };

  const handleEdit = (role) => {
    form.setFieldsValue({
      name: role.name,
      permissions: role.permissions,
    });
    setEditingRole(role);
    setIsModalOpen(true);
  };

  const handleSave = () => {
    form.validateFields().then(values => {
      const newRole = {
        id: editingRole?.id || Date.now().toString(),
        name: values.name,
        permissions: values.permissions,
      };

      if (editingRole) {
        setRoles(roles.map(r => r.id === editingRole.id ? newRole : r));
        message.success('角色已更新');
      } else {
        setRoles([...roles, newRole]);
        message.success('新角色已创建');
      }

      setIsModalOpen(false);
    });
  };

  const handleDelete = (roleId) => {
    setRoles(roles.filter(r => r.id !== roleId));
    message.success('角色已删除');
  };

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '权限',
      dataIndex: 'permissions',
      key: 'permissions',
      render: (permissions) => (
        <>
          {permissions.map(permission => {
            const permissionObj = permissionsList.find(p => p.key === permission);
            return permissionObj ? (
              <Tag key={permission} color="blue">
                {permissionObj.name}
              </Tag>
            ) : null;
          })}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button size="small" onClick={() => handleEdit(record)}>编辑</Button>
          <Button
            size="small"
            danger
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
          添加角色
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={roles}
        rowKey="id"
        pagination={false}
      />

      <Modal
        title={editingRole ? "编辑角色" : "添加新角色"}
        open={isModalOpen}
        onOk={handleSave}
        onCancel={() => setIsModalOpen(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="输入角色名称" />
          </Form.Item>

          <Form.Item
            name="permissions"
            label="选择权限"
          >
            <Checkbox.Group style={{ display: 'flex', flexDirection: 'column' }}>
              {permissionsList.map(permission => (
                <Checkbox
                  key={permission.key}
                  value={permission.key}
                  style={{ lineHeight: '32px' }}
                >
                  {permission.name}
                </Checkbox>
              ))}
            </Checkbox.Group>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default RoleList;
